package com.example.diedi;

import android.media.Image;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private ImageView imgAll;
    private Button btnNext;
    private int allimg[]={R.drawable.dog1,R.drawable.dog2,
            R.drawable.dog3,R.drawable.dog4,R.drawable.dog5};
    private int index=0;
    private Handler handler;
    private final  int Msg_Change_img=1001;
    private boolean isPause=true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.what==Msg_Change_img){
                    index =(index+1)%allimg.length;
                    imgAll.setImageResource(allimg[index]);
                    return  true;
                }
                return false;
            }
        });
        imgAll=findViewById(R.id.imgAll);
        btnNext=findViewById(R.id.btnNext);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    try{
                        Thread.sleep(2000);
                    }catch (
                            InterruptedException e
                            ){
                        e.printStackTrace();
                    }
                    if(!isPause){
                        Message message=new Message();
                        message.what=Msg_Change_img;
                        handler.sendMessage(message);
                    }
                }
            }
        }).start();
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isPause=!isPause;
            }
        });
    }
}
